package model

import (
	"adai.design/homeserver/home/data"
	"errors"
)

type Accessory struct {
	UUID     		string      `json:"aid" bson:"aid"`
	Type     		int         `json:"type" bson:"type"`
	IsReachable  	bool		`json:"-" bson:"-"`
	Services 		[]*Service 	`json:"services" bson:"services"`
}

func (a *Accessory) SetReachable(reachable bool) {
	a.IsReachable = reachable
}

func (a *Accessory) RefreshCharacteristic(char *data.Characteristic) error {
	a.IsReachable = true
	for _, s := range a.Services {
		if char.SId == s.ID {
			for _, c := range s.Characteristics {
				if c.Id == char.CId {
					c.Value = char.Value
					return nil
				}
			}
		}
	}
	return errors.New("characteristic 404 not found")
}

func (a *Accessory) GetCharacteristics() []*data.Characteristic {
	if !a.IsReachable {
		return nil
	}
	var chars []*data.Characteristic
	for _, s := range a.Services {
		for _, c := range s.Characteristics {
			char := &data.Characteristic{
				AId:   a.UUID,
				SId:   s.ID,
				CId:   c.Id,
				Value: c.Value,
			}
			if char.Value == nil {
				char.Value = 0
			}
			chars = append(chars, char)
		}
	}
	return chars
}